#!/bin/bash
echo "🔧 修复 cbp2make.cpp 语法..."

# 备份
cp src/cbp2make.cpp src/cbp2make.cpp.backup3

# 找到main函数的开始和结束
MAIN_START=$(grep -n "int main(int argc, char\* argv\[\])" src/cbp2make.cpp | cut -d: -f1)
MAIN_END=$(grep -n "^}.*//.*main" src/cbp2make.cpp | head -1 | cut -d: -f1)

if [ -n "$MAIN_START" ] && [ -n "$MAIN_END" ]; then
    # 删除之前错误的AI代码
    sed -i '/if (argc > 1 && std::string(argv\[1\]) == "--ai-mode")/,/return 0;/d' src/cbp2make.cpp
    
    # 在main函数内正确位置插入AI代码（在PM.Initialize之前）
    sed -i '/PM\.Initialize(argc,argv);/i\
    // AICoder 增强模式\
    if (argc > 1 && std::string(argv[1]) == "--ai-mode") {\
        std::cout << "AI Mode: Analyzing project with AI enhancement" << std::endl;\
        return 0;\
    }' src/cbp2make.cpp
else
    echo "❌ 找不到main函数，手动修复..."
    # 手动修复
    cat > src/cbp2make_fixed.cpp << 'MANUAL_FIX'
#include "cbp2make.h"
#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    // AICoder 增强模式
    if (argc > 1 && std::string(argv[1]) == "--ai-mode") {
        std::cout << "AI Mode: Analyzing project with AI enhancement" << std::endl;
        return 0;
    }

    CCodeBlocksBuildManager PM;
    PM.Initialize(argc,argv);
    PM.Run();
    PM.Finalize();
    return 0;
}
MANUAL_FIX
    # 这里需要更复杂的修复，先跳过
    echo "⚠️  需要手动修复 cbp2make.cpp"
fi

echo "✅ 语法修复尝试完成"
